import { fileURLToPath, URL } from 'node:url'

import { ConfigEnv, defineConfig, PluginOption } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'

import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
//@ts-ignore
import vitePluginImp from 'vite-plugin-imp'
import { lazyImport, VxeResolver } from 'vite-plugin-lazy-import'

import legacy from '@vitejs/plugin-legacy'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { resolve } from 'node:path'

// https://vitejs.dev/config/
const antdVueResolver = AntDesignVueResolver({ importStyle: 'less' })
export default defineConfig((env: ConfigEnv) => {
  console.log('env', env)
  const otherPlugins: PluginOption[] = []
  if (env.command === 'serve') {
    otherPlugins.push(vueDevTools())
  } else {
    otherPlugins.push(
      legacy({
        targets: ['defaults', 'not IE 11', 'Chrome >= 75'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime']
      })
    )
  }
  return {
    plugins: [
      vue(),
      vueJsx(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [resolve(process.cwd(), 'src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      }),
      AutoImport({
        imports: ['vue', 'vue-router'], // 自动导入vue和vue-router相关函数
        dts: 'src/auto-import.d.ts', // 生成 `auto-import.d.ts` 全局声明
        resolvers: [antdVueResolver]
      }),
      Components({
        // 指定组件所在文件夹的位置，默认是src/components
        dirs: ['src/components'],
        resolvers: [antdVueResolver],
        // 配置type文件生成位置
        dts: 'src/components.d.ts'
      }),
      vitePluginImp({
        libList: [
          {
            libName: 'ant-design-vue',
            style(name: string) {
              // use less
              return `ant-design-vue/es/${name}/style/index.js`
            }
          }
        ]
      }),
      lazyImport({
        resolvers: [
          VxeResolver({
            libraryName: 'vxe-table'
          })
          // VxeResolver({
          //   libraryName: 'vxe-pc-ui'
          // })
        ]
      }),
      ...otherPlugins
    ],
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            // 在这里自定义主题色等样式
            // 'primary-color': '#1da57a',
            // 'link-color': '#1da57a',
            // 'border-radius-base': '2px'
          },
          javascriptEnabled: true
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    }
  }
})
